package com.xuanyue.db.xuan.antlr.v2.function;

import java.util.List;

import com.xuanyue.db.xuan.core.index.ListObject;
import com.xuanyue.db.xuan.core.table.IBitIndex;
import com.xuanyue.db.xuan.core.table.expr.Expr;
import com.xuanyue.db.xuan.core.table.expr.ExprValue;
import com.xuanyue.db.xuan.core.table.expr.ExprValueType;
import com.xuanyue.db.xuan.core.table.expr.IFunctionExecutor;
/**
 * 包含给定数组
 *
 * @author 解观海
 * @email guanhaixie@sina.cn
 * @date 2021年1月21日
 *
 */
public class ListObjectContainsFunction implements IFunctionExecutor<ListObject<?>> {

	@Override
	public void exprExe(ListObject<?> column, ExprValue v, List<IBitIndex> caches) {
		Expr expr = new Expr();
		expr.setOp("=");
		List<ExprValue> tar = v.getValue();
		IBitIndex r = caches.get(0);
		if(tar.size()>column.getListSize()) {
			r.setAll(false);
			return;
		}
		
		int size = column.getListSize();
		int[] indexs = new int[3];
		expr.setArryIndex(indexs);
		indexs[1]=1;
		expr.setValue(v);
		
		IBitIndex rTmp = caches.get(1);
		r.setAll(false);
		caches = caches.subList(1, caches.size());
		for(int i=0,ts=tar.size(),s=size-ts+1;i<s;i++) {
			indexs[0]=i;
			indexs[2]=i+ts;
			column.exe(expr, caches);
			r.or(rTmp);
		}
	}

	@Override
	public int exprCheck(ListObject<?> column, ExprValue v) {
		if(!ExprValueType.ARRAY.is(v.getType())) {
			return 0;
		}
		List<ExprValue> tar = v.getValue();
		Expr expr = new Expr();
		expr.setOp("=");
		expr.setArryIndex(new int[] {0,0,0});
		int s=0;
		for(ExprValue ev:tar) {
			expr.setValue(ev);
			s = column.checkAndContSource(expr);
			if(s==0) {
				return 0;
			}
		}
		if(tar.size()>column.getListSize()) {
			return 1;
		}
		return s+1;
	}
}
